package com.wswy.wzcx.ui.web;

import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alipay.sdk.app.H5PayCallback;
import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.util.H5PayResultModel;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdDislike.DislikeInteractionCallback;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdNative.NativeExpressAdListener;
import com.bytedance.sdk.openadsdk.TTBannerAd;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.che.libcommon.utils.RxBus;
//import com.qq.e.ads.banner.ADSize;
//import com.qq.e.ads.banner.BannerView;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebBackForwardList;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.BuildConfig;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.AdModel;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.news.NewsModel;
import com.wswy.wzcx.module.ChannelManager;
import com.wswy.wzcx.module.GlobalConfigManager;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.InternalMsgCodeKt;
import com.wswy.wzcx.module.ad.AdConfigLoader;
import com.wswy.wzcx.module.ad.TTAdManagerHolder;
import com.wswy.wzcx.module.base.CBaseActivity;
import com.wswy.wzcx.module.base.UserViewModel;
import com.wswy.wzcx.ui.Constants;
import com.wswy.wzcx.ui.adapter.NewsAdapter3;
import com.wswy.wzcx.ui.data.PayResult;
import com.wswy.wzcx.utils.NetUtils;
import com.wswy.wzcx.utils.ShareDialog;
import com.wswy.wzcx.utils.ShareHelper;
import com.wswy.wzcx.widget.JCInterface;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import timber.log.Timber;


public class WebViewActivity extends CBaseActivity implements Toolbar.OnMenuItemClickListener, IAdWeb {
    private static final String APP_CACHE_DIRNAME = "/webcache"; // web缓存目录

    public static void startWebview(Context context, String url) {
        startWebview(context, url, true);
    }

    public static void startWebview(Context context, String url, boolean showToolBar) {
        startWebview(context, context.getString(R.string.app_name), url, showToolBar);
    }

    public static void startWebview(Context context, String title, String url, boolean showToolBar) {
        Intent intent = new Intent(context, WebViewActivity.class);
//        intent.putExtra("data", url);
//        intent.putExtra("title", title);
//        intent.putExtra("showToolBar", showToolBar);
        WebPageArgument webPageArgument = new WebPageArgument(url);
        webPageArgument.setTitle(title).setShowToolBar(showToolBar);
        intent.putExtra(Constants.EXTRA_DATA, webPageArgument);
        context.startActivity(intent);
    }

    @Deprecated
    public static void startWebview(Context context, String title, String url, boolean showToolBar, boolean showShare, boolean showAd, boolean showUrlTitle) {
        Intent intent = new Intent(context, WebViewActivity.class);
//        intent.putExtra("data", url);
//        intent.putExtra("title", title);
//        intent.putExtra("showToolBar", showToolBar);
//        intent.putExtra("showAd", showAd);
//        intent.putExtra("showShare", showShare);
//        intent.putExtra("showUrlTitle",showUrlTitle);
        WebPageArgument webPageArgument = new WebPageArgument(url);
        webPageArgument.setTitle(title)
                .setShowToolBar(showToolBar)
                .setShowAd(showAd)
                .setShowShare(showShare)
                .setShowUrlTitle(showUrlTitle)
                .setShowNestedAd(true);
        intent.putExtra(Constants.EXTRA_DATA, webPageArgument);
        context.startActivity(intent);
    }


    private static final int REQ_CHOOSE_FILE = 2;

    private BaseWebView mWebView;
    private ProgressBar progressBar;
    private TextView tvTitle;
    private Toolbar toolbar;

    private WebPageArgument mPageArgument;

    private String webTitle;
    private boolean firstLoadedTitle = false;


    //文件上传
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;


    private boolean finishedFlag = false;
    private TTNativeExpressAd ttadBv;
    private Runnable adRunnable;

    private PayTask aliPayTask;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPageArgument = getIntent().getParcelableExtra(Constants.EXTRA_DATA);
        if (mPageArgument == null || TextUtils.isEmpty(mPageArgument.getUrl())) {
            finish();
            return;
        }
        if (needRecommendNews()) {
            setContentView(R.layout.activity_web2_nsad);
        } else {
            setContentView(R.layout.activity_web2);
        }

        mWebView = findViewById(R.id.webview);
        progressBar = findViewById(R.id.progress_bar);
        tvTitle = findViewById(R.id.tv_title);
        toolbar = findViewById(R.id.toolbar);

        NestedScrollView nsView = findViewById(R.id.ns_view);
        if (nsView != null) {
            nsView.setNestedScrollingEnabled(false);
        }
//        if (NetUtils.isNetworkAvailable(this)) {
//            mWebView.clearCache(true);
//        }
        configParams();
        configWebview();
        handleBannerAd();
        if (!DataCenter.get().hasLogin()) {
            UserViewModel userViewModel = provideViewModel(UserViewModel.class);
            userViewModel.registerObservers();
            userViewModel.getUserLiveData().observe(this,
                    new Observer<UserMode>() {
                        @Override
                        public void onChanged(@Nullable UserMode userMode) {
                            if (userMode != null && !TextUtils.isEmpty(userMode.token)) {
                                firstLoad();
                            }
                        }
                    });
        }
    }

    private void configParams() {
        if (mPageArgument.isH5Pay()) {
            if (aliPayTask == null) {
                aliPayTask = new PayTask(this);
            }
        }
        if (mPageArgument.isShowToolBar()) {
            findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
            if (!TextUtils.isEmpty(mPageArgument.getTitle()))
                tvTitle.setText(mPageArgument.getTitle());
            setSupportActionBar(toolbar);
            toolbar.setOnMenuItemClickListener(this);
            final ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayShowTitleEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setDisplayShowHomeEnabled(true);
            }
        } else {
            findViewById(R.id.appbar).setVisibility(View.GONE);

        }
        //刷新状态
        registerEvent(InternalMsgCodeKt.ORDER_STATUS_CHANGED, new Function1<Object, Unit>() {
            @Override
            public Unit invoke(Object o) {
                firstLoad();
                return null;
            }
        });

    }

    private void configWebview() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        WebSettings webSettings = mWebView.getSettings();
        //设置缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 开启DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        // 开启database storage API功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACHE_DIRNAME;
        // 设置数据库缓存路径
        webSettings.setAppCachePath(cacheDirPath);
        webSettings.setAppCacheEnabled(true);
        //支持缩放，默认为true。
        webSettings.setSupportZoom(false);
        //调整图片至适合webview的大小
        webSettings.setUseWideViewPort(true);
        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
        //设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new JCInterface(this), "CcJsBridge");
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //支付宝h5拦截
                if (url != null && mPageArgument.isH5Pay() && url.contains("alipay.com")) {
                    if (aliPayTask != null) {
                        boolean isIntercepted = aliPayTask.payInterceptorWithUrl(url, true, new H5PayCallback() {

                            @Override
                            public void onPayResult(H5PayResultModel result) {
                                String resultCode = result.getResultCode();
                                final String url = result.getReturnUrl();
                                PayResult payResult = PayResult.buildFromAlipay(resultCode);
                                RxBus.getDefault().postWithCode(InternalMsgCode.CODE_PAY_RESULT, payResult);
                                finish();
                            }
                        });
                        if (isIntercepted) {
                            return true;
                        }
                    }
                }

                if (url.startsWith("weixin://") || url.startsWith("alipay") || url.startsWith("tel:")) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        if (intent.resolveActivity(getPackageManager()) != null) {
                            startActivity(intent);
                            return true;
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    return super.shouldOverrideUrlLoading(view, url);
                } else {
                    //只处理http请求
                    if (url.startsWith("http://") || url.startsWith("https://")) {
                        //view.loadUrl(url);
                        if (mWebView.isTouchByUser()) {
                            view.loadUrl(url);
                        } else {
                            //301/302 处理，非用户手动点击 不要加到回退栈中
                            return super.shouldOverrideUrlLoading(view, url);
                        }

                    } else {
                        handleURL(url);
                    }

                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                progressBar.setVisibility(View.VISIBLE);
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.GONE);
                invalidateOptionsMenu();
                onLoadFinish(url);
                finishedFlag = true;
                if (adRunnable != null) {
                    adRunnable.run();
                }
                adRunnable = null;
            }


        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress >= 95) {
                    progressBar.setVisibility(View.GONE);
                    finishedFlag = true;
                    if (adRunnable != null) {
                        adRunnable.run();
                    }
                    adRunnable = null;
                } else {
                    progressBar.setProgress(newProgress);
                }


            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                webTitle = title;
                firstLoadedTitle = true;
                if (mPageArgument.isShowUrlTitle()) {
                    tvTitle.setText(title);
                }
                invalidateOptionsMenu();
            }

            @Override
            public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
                super.openFileChooser(valueCallback, acceptType, capture);

                uploadFile = valueCallback;
                openFileChooseProcess();
            }

            public boolean onShowFileChooser(WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }
        });
        firstLoad();
        CookieSyncManager.createInstance(getApplicationContext());
        CookieSyncManager.getInstance().sync();
    }

    private void firstLoad() {
        Map<String, String> headers = new HashMap<>(4);
        headers.put("X-from-app", "android");
        headers.put("X-app-version", String.valueOf(BuildConfig.VERSION_CODE));
        headers.put("X-channel", ChannelManager.getChannel());

        if ((mPageArgument.isAddToken() || isInternalURL(mPageArgument.getUrl())) && DataCenter.get().hasLogin()) {
            headers.put("X-token", DataCenter.get().getUserMode().token);
        }
        if (!TextUtils.isEmpty(mPageArgument.getReferer())) {
            headers.put("Referer", mPageArgument.getReferer());
        }
        mWebView.loadUrl(mPageArgument.getUrl(), headers);
    }


    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "选择文件"), REQ_CHOOSE_FILE);
    }

    private boolean isInternalURL(String url) {
        return !TextUtils.isEmpty(url) && GlobalConfigManager
                .getInstance().isWhitelistHost(Uri.parse(url).getHost());
    }

    private void handleURL(String url) {
        if (!TextUtils.isEmpty(url)) {
            if (url.startsWith("tbopen://") || url.startsWith("taobao://")) {
                handleTaobao(Uri.parse(url));
            }

        }
    }

    private void handleTaobao(Uri uri) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(uri);
            intent.setPackage("com.taobao.taobao");
            startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share:
                showShareDialog();
                break;
        }
        return true;
    }

    private void showShareDialog() {
        new ShareDialog(this, new ShareDialog.OnChooseShareTypeCallback() {
            @Override
            public void onChooseType(int shareType) {
                ShareHelper.shareUrl(AppContext.getContext(), shareType, mPageArgument.getUrl(), webTitle, getString(R.string.default_share_url_desc), null);
            }
        }).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (mPageArgument.isShowShare() && firstLoadedTitle) {
            getMenuInflater().inflate(R.menu.menu_share, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CHOOSE_FILE) {
            if (resultCode == Activity.RESULT_OK) {
                Uri result = data == null ? null : data.getData();

                if (uploadFile != null) {
                    uploadFile.onReceiveValue(result);
                    uploadFile = null;
                }
                if (uploadFiles != null) {
                    uploadFiles.onReceiveValue(new Uri[]{result});
                    uploadFiles = null;
                }

            } else {

                if (uploadFile != null) {
                    uploadFile.onReceiveValue(null);
                    uploadFile = null;
                }
                if (uploadFiles != null) {
                    uploadFiles.onReceiveValue(null);
                    uploadFiles = null;
                }

            }

        }

    }

    @Override
    protected void onDestroy() {
        if (mWebView != null) {
//            if (progressBar.isActivated()) {
//                progressBar.setVisibility(View.GONE);
//                progressBar = null;
//            }
//            if (progressBar.getVisibility() == View.VISIBLE) {
//                progressBar.setVisibility(View.v);
//                progressBar.setVisibility(View.GONE);
//            }
            // 如果先调用destroy()方法，则会命中if (isDestroyed()) return;这一行代码，需要先onDetachedFromWindow()，再
            // destory()
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.stopLoading();
            // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
            mWebView.getSettings().setJavaScriptEnabled(false);
            mWebView.clearHistory();
            mWebView.clearView();
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
        if (ttadBv != null) {
            ttadBv.destroy();
        }
        adRunnable = null;
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mPageArgument.isH5Pay()) {
            finish();
            return;
        }
        if (mWebView.canGoBack()) {
            //获取webView的浏览记录
            WebBackForwardList mWebBackForwardList = mWebView.copyBackForwardList();
            //这里的判断是为了让页面在有上一个页面的情况下，跳转到上一个html页面，而不是退出当前activity
            if (mWebBackForwardList.getCurrentIndex() > 0) {
                mWebView.goBack();
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }

    }

    private void handleBannerAd() {
        if (mPageArgument.isShowBannerAd()) {
            AdModel newsBannerAd = GlobalConfigManager.getInstance().getAdsConf().getNewsBannerAd();
            if (newsBannerAd != null) {
                switch (newsBannerAd.type) {
                    case AdModel.GDT:
                        showGDTBannerAd();
                        break;
                    case AdModel.TTAD:
                        showTTADBannerAd();
                        break;
                }
            }
        }
    }

    private boolean needRecommendNews() {
        try {
            return Uri.parse(mPageArgument.getUrl()).getHost().contains("autohome.com");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }


    private boolean ffinisded = false;

    private void onLoadFinish(String url) {
        if (ffinisded) {
            return;
        }
        ffinisded = true;
        if (needRecommendNews()) {
            new AdWebPresenter(getApplicationContext(), this).load();
        }
    }

    private void showGDTBannerAd() {
        FrameLayout flAd = findViewById(R.id.fl_banner_ad);
        if (flAd == null) {
            return;
        }
//        BannerView bv = new BannerView(this, ADSize.BANNER,
//                AdConfigLoader.getGdtConfig().getAppId(), "3020645845044414");
//        bv.setShowClose(true);
//        flAd.addView(bv);
//        bv.loadAD();
    }

    private void showTTADBannerAd() {
        final FrameLayout flAd = findViewById(R.id.fl_banner_ad);
        if (flAd == null) {
            return;
        }
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId("903230456")
                .setNativeAdType(AdSlot.TYPE_BANNER)
                .setSupportDeepLink(true)
                .setExpressViewAcceptedSize(SizeUtils.px2dp(ScreenUtils.getAppScreenWidth()), 60)
                .setImageAcceptedSize(600, 150)
                .setAdCount(1)
                .build();

        TTAdManagerHolder.getInstance(getApplicationContext()).createAdNative(this).loadBannerExpressAd(
                adSlot, new NativeExpressAdListener() {
                    @Override
                    public void onError(int i, String s) {
                        Timber.e("ttad error  " + i + "  " + s);
                    }

                    @Override
                    public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                        if (list != null && !list.isEmpty()) {
                            ttadBv = list.get(0);
                            if (ttadBv == null) {
                                return;
                            }
                            ttadBv.setDislikeCallback(WebViewActivity.this,
                                    new DislikeInteractionCallback() {
                                        @Override
                                        public void onSelected(int i, String s) {
                                            flAd.removeAllViews();
                                        }

                                        @Override
                                        public void onCancel() {

                                        }

                                        @Override
                                        public void onRefuse() {

                                        }
                                    });
                            ttadBv.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {

                                @Override
                                public void onAdClicked(View view, int i) {

                                }

                                @Override
                                public void onAdShow(View view, int i) {

                                }

                                @Override
                                public void onRenderFail(View view, String s, int i) {

                                }

                                @Override
                                public void onRenderSuccess(final View view, float v, float v1) {
                                    if (finishedFlag) {
                                        flAd.removeAllViews();
                                        flAd.addView(view);
                                    } else {
                                        adRunnable = new Runnable() {
                                            @Override
                                            public void run() {
                                                flAd.removeAllViews();
                                                flAd.addView(view);
                                            }
                                        };
                                    }

                                }
                            });

                            ttadBv.render();
                        }
                    }
                });


    }

    @Override
    public void showNews(List<NewsModel> list) {
        //显示新闻列表
        LinearLayout llContent = findViewById(R.id.ll_web_content);
        if (llContent == null) {
            return;
        }
        RecyclerView recyclerView = new RecyclerView(this);
        recyclerView.setBackgroundColor(Color.WHITE);

        TextView tvR = new TextView(this);
        tvR.setTextColor(ContextCompat.getColor(this, R.color.textColorPrimary));
        tvR.setTextSize(15);
        tvR.setText("相关推荐");
        tvR.getPaint().setFakeBoldText(true);
        tvR.setPadding(SizeUtils.dp2px(16), SizeUtils.dp2px(12), 0, 0);
        tvR.setBackgroundColor(Color.WHITE);


        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.topMargin = SizeUtils.dp2px(10);

        llContent.addView(tvR, lp);


        lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        llContent.addView(recyclerView, lp);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        NewsAdapter3 adapter3 = new NewsAdapter3(null, null, null);

        recyclerView.setAdapter(adapter3);
        List data = list;

        adapter3.setNewData(data);
        adapter3.notifyDataSetChanged();

    }
}
